﻿using System;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Telerik.Web.UI;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;
using KPIS.GERP.GHRMS.APP.Classes;
using KPIS.GERP.GHRMS.APP.Reports;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class PS_EmployeesInfo : System.Web.UI.Page
    {
        private IEmployeeBLL empBLL = new EmployeeBLL();
        private IEmployeeTypeBLL et = new EmployeeTypeBLL();
        private ICommandDetailBLL cmdBLL = new CommandDetailBLL();
        private IHisEducationBLL eduBLL = new HisEducationBLL();
        private IRoyalItemHistoriesBLL royBLL = new RoyalItemHistoriesBLL();
        private ISpecialSkillBLL skillBLL = new SpecialSkillBLL();
        private IAbsenceBLL abBLL = new AbsenceBLL();
        private IHisSpouseBLL spouBLL = new HisSpouseBLL();
        private ITrainingBLL trBLL = new TrainingBLL();
        private ILegateeBLL lgBLL = new LegateeBLL();
        private IIncreaseBLL icBLL = new IncreaseBLL();
        private IHisGoodNessBLL gnBLL = new HisGoodNessBLL();
        private IHisNameBLL nameBLL = new HisNameBLL();
        private IEmployeeStatusBLL esBLL = new EmployeeStatusBLL();
        private IJobSiteTypeBLL jtBLL = new JobSiteTypeBLL();
        private Main main = new Main();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindEmpType();
                BindEmployeeStatus();

                //=================== test ====================
                if (Request.QueryString["emptype"] != null)
                {
                    ddlEmployeeType.SelectedValue = Request.QueryString["emptype"];
                    ddlEmployeeType_SelectedIndexChanged(null ,null);
                }
                //=============================================
                imbRefresh_Click(sender, new ImageClickEventArgs(0,0));
            }
        }
        private void BindEmpType()
        {
            try
            {
                IList<EmployeeTypeInfo> infoList = et.ListEmployeeTypes();
                ddlEmployeeType.DataSource = infoList;
                ddlEmployeeType.DataBind();
                ddlEmployeeType.Items.Insert(0, new RadComboBoxItem("--เลือกประเภทบุคลากร--", ""));

                if (ddlEmployeeType.Items.Count > 0)
                {
                    ddlEmployeeType.SelectedIndex = 1;
                }
                
                //if (String.IsNullOrEmpty(ddlEmployeeType.SelectedValue) && ddlEmployeeType.Items.Count > 0 && ddlEmployeeType.FindItemByValue("-1") != null)
                //{
                //    ddlEmployeeType.SelectedIndex = ddlEmployeeType.FindItemByValue("-1").Index; 
                //    ddlEmployeeType.FindItemByValue("-1").CssClass = "RoundBoxBlue";
                //}
            }
            catch
            {


            }
        }
        private void BindEmployeeStatus()
        {
            try
            {
                IList<EmployeeStatusInfo> infoList = esBLL.LoadListEmployeeStatusGroupByActive(); 
                ddlEmployeeStatus.DataSource = infoList;
                ddlEmployeeStatus.DataBind();

                foreach (RadComboBoxItem i in ddlEmployeeStatus.Items)
                {
                    if(i.Value == "-1") // แสดงทั้งหมด
                    {
                        i.CssClass = "RoundBoxBlue";
                    }
                    else if (i.Value == "-2") // แสดง Active Employee
                    {
                        i.CssClass = "RoundBoxGreen";
                    }
                    else if (i.Value == "-3") // แสดง Inactive Employee
                    {
                        i.CssClass = "RoundBoxGreen";
                    } 
                }

                if (String.IsNullOrEmpty(ddlEmployeeStatus.SelectedValue) && ddlEmployeeStatus.Items.Count > 0)
                    ddlEmployeeStatus.SelectedValue = "-2";
            }
            catch
            {

            }
        }
        private void LoadGrid()
        {
            DataSet ds = null;
            DataTable dt = null;
            //แก้ไม่ให้โหลด data หากไม่เลือก ddlEmployeeType
            //string employeeTypeSelected = ddlEmployeeType.SelectedValue == "-1" ? "" : ddlEmployeeType.SelectedValue;
            //ds = empBLL.LoadEmployees((int?)null, employeeTypeSelected, true, "", ddlEmployeeStatus.SelectedValue);
            //dt = ds.Tables[0].Copy();

            string strEmployeeTypeSeq = ddlEmployeeType.SelectedValue;
            Session["EmpType"] = ddlEmployeeType.SelectedValue;
            if (!string.IsNullOrEmpty(strEmployeeTypeSeq))
            {
                ds = empBLL.LoadEmployees((int?)null, strEmployeeTypeSeq, true, "", ddlEmployeeStatus.SelectedValue);
                dt = ds.Tables[0].Copy();
            }
            else
            {
            }

            RadGrid1.DataSource = dt;
            RadGrid1.DataBind();
        }


        protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridNestedViewItem)
            {
                //e.Item.FindControl("InnerContainer").Visible = ((GridNestedViewItem)e.Item).ParentItem.Expanded;
            }

        }
        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.ExpandCollapseCommandName)
            {
                Session["emp_seq"] = ((Label)((GridDataItem)e.Item).ChildItem.FindControl("lblEmpSeq")).Text;
            }
            else if (e.CommandName == "PrintInfo")
            {
                #region print1
                DataSet ds = null;
                DataTable dt = null;
                DataSet[] dsSubReport;
                DataTable[] dtSubReport;
                string[] strSubReportName;

                string strEmpSequence = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["emp_seq"].ToString();                 

                strSubReportName = new string[14];
                dsSubReport = new DataSet[14];
                dtSubReport = new DataTable[14];

                ds = empBLL.LoadEmployees(Convert.ToInt32(strEmpSequence), "", true, "");
                if (ds.Tables.Count > 0)
                    dt = ds.Tables[0].Copy();

                //ประวัติการรับราชการ                    
                strSubReportName[0] = "RPT_PS_HisPositions";
                dsSubReport[0] = cmdBLL.LoadCommandDetails(Convert.ToInt32(strEmpSequence), SystemInfo._HisPosition);
                if (dsSubReport[0].Tables.Count > 0)
                    dtSubReport[0] = dsSubReport[0].Tables[0].Copy();

                //ประวัติการเลื่อนเงินเดือน         
                strSubReportName[1] = "RPT_PS_HisSalary";
                dsSubReport[1] = cmdBLL.LoadCommandDetails(Convert.ToInt32(strEmpSequence), SystemInfo._HisSalary);
                if (dsSubReport[1].Tables.Count > 0)
                    dtSubReport[1] = dsSubReport[1].Tables[0].Copy();

                //ประวัติการรับเงินเพิ่มพิเศษ   
                strSubReportName[2] = "RPT_PS_HisSalaryExtra";
                dsSubReport[2] = cmdBLL.LoadCommandDetails(Convert.ToInt32(strEmpSequence), SystemInfo._HisSalary);
                if (dsSubReport[2].Tables.Count > 0)
                    dtSubReport[2] = dsSubReport[2].Tables[0].Copy();

                //ประวัติการศึกษา      
                strSubReportName[3] = "RPT_PS_HisEducate";
                dsSubReport[3] = eduBLL.LoadEducationHistories((int?)null, strEmpSequence);
                if (dsSubReport[3].Tables.Count > 0)
                    dtSubReport[3] = dsSubReport[3].Tables[0].Copy();

                //ประวัติการฝึกอบรม               
                strSubReportName[4] = "RPT_PS_HisTraining";
                dsSubReport[4] = trBLL.LoadTrainingHistories(Int32.Parse(strEmpSequence));
                if (dsSubReport[4].Tables.Count > 0)
                    dtSubReport[4] = dsSubReport[4].Tables[0].Copy();

                //ความสามารถพิเศษ  
                strSubReportName[5] = "RPT_PS_SpecialSkill";
                dsSubReport[5] = skillBLL.LoadSpecialSkill(null, Int32.Parse(strEmpSequence));
                if (dsSubReport[5].Tables.Count > 0)
                    dtSubReport[5] = dsSubReport[5].Tables[0].Copy();

                //ข้อมูลทายาท  
                strSubReportName[6] = "RPT_PS_Legatees";
                dsSubReport[6] = lgBLL.LoadLegatee(null, Int32.Parse(strEmpSequence));
                if (dsSubReport[6].Tables.Count > 0)
                    dtSubReport[6] = dsSubReport[6].Tables[0].Copy();

                //ประวัติการลา สาย ขาด  
                strSubReportName[7] = "RPT_PS_HisAbsences";
                dsSubReport[7] = abBLL.LoadAbsences(null, Int32.Parse(strEmpSequence));
                if (dsSubReport[7].Tables.Count > 0)
                    dtSubReport[7] = dsSubReport[7].Tables[0].Copy();

                //ประวัติทางวินัย
                strSubReportName[8] = "RPT_PS_HisDiscipline";
                dsSubReport[8] = cmdBLL.LoadCommandDetails(Convert.ToInt32(strEmpSequence), SystemInfo._HisDiscipline);
                if (dsSubReport[8].Tables.Count > 0)
                    dtSubReport[8] = dsSubReport[8].Tables[0].Copy();

                //ประวัติเวลาทวีคูณ  
                strSubReportName[9] = "RPT_PS_HisIncrease";
                dsSubReport[9] = icBLL.LoadHisIncrease(null, Int32.Parse(strEmpSequence));
                if (dsSubReport[9].Tables.Count > 0)
                    dtSubReport[9] = dsSubReport[9].Tables[0].Copy();

                //ประวัติการรับความดีความชอบ  
                strSubReportName[10] = "RPT_PS_HisGoodNess";
                dsSubReport[10] = gnBLL.LoadHisGoodNess(null, Int32.Parse(strEmpSequence));
                if (dsSubReport[10].Tables.Count > 0)
                    dtSubReport[10] = dsSubReport[10].Tables[0].Copy();

                //ประวัติการสมรส  
                strSubReportName[11] = "RPT_PS_HisSpouses";
                dsSubReport[11] = spouBLL.LoadSpouse(null, Int32.Parse(strEmpSequence));
                if (dsSubReport[11].Tables.Count > 0)
                    dtSubReport[11] = dsSubReport[11].Tables[0].Copy();

                //ประวัติการเปลี่ยนแปลงชื่อ - สกุล  
                strSubReportName[12] = "RPT_PS_HisName";
                dsSubReport[12] = nameBLL.LoadHisNames(null, Int32.Parse(strEmpSequence));
                if (dsSubReport[12].Tables.Count > 0)
                    dtSubReport[12] = dsSubReport[12].Tables[0].Copy();

                //ประวัติการรับเครื่องราช
                strSubReportName[13] = "RPT_PS_HisRoyalItems";
                dsSubReport[13] = royBLL.LoadRoyalItemHistories((int?)null, Int32.Parse(strEmpSequence), (int?)null);
                if (dsSubReport[13].Tables.Count > 0)
                    dtSubReport[13] = dsSubReport[13].Tables[0].Copy();

                Session["strSubReportName"] = strSubReportName;
                Session["dtSubReport"] = dtSubReport;
                Session["dtReport"] = dt;
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "onclick", "openReport()", true);
                #endregion
            }

           LoadGrid();

        }
 
        protected void RadGrid1_PageIndexChanged(object source, GridPageChangedEventArgs e)
        {

        }

        protected void ddlEmployeeType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            Session["EmpType"] = ddlEmployeeType.SelectedValue;
            LoadGrid();
        }  

        protected void imbRefresh_Click(object sender, ImageClickEventArgs e)
        {
            LoadGrid();
        }

        protected void ddlEmployeeStatus_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadGrid();
        }

        protected void cmdPrint2_Click(object sender, EventArgs e)
        {
            if (RadGrid1.SelectedItems.Count > 0)
            {
                int nEmpSeq = main.ConvertNullInt(main.WebString(((GridDataItem)RadGrid1.SelectedItems[0])["emp_seq"].Text)) ?? 0;
                DataTable dtb = empBLL.LoadEmployees(nEmpSeq, "", true, "").Tables[0];

                if (dtb.Rows.Count > 0)
                {
                    DataRow dr = dtb.Rows[0];
                    Dictionary<string, string> dic = new Dictionary<string, string>();

                    IList<JobSiteTypeInfo> dtbDepJobSite = jtBLL.ListJobSiteTypes(1);

                    if (dtbDepJobSite.Count > 0)
                    {
                        dic.Add("A3", "กระทรวง " + dtbDepJobSite[0].CurrentUpperJobSiteName);
                        dic.Add("D3", "กรม " + dtbDepJobSite[0].CurrentJobSiteName);
                    }

                    string strCitizenId = dr["CITIZEN"].ToString().Trim().Replace("-", "").Replace(" ", "");

                    if (strCitizenId.Length == 13)
                    {
                        strCitizenId = strCitizenId.Insert(1, "-").Insert(6, "-").Insert(12, "-").Insert(15, "-");
                    }

                    dic.Add("C4", dr["PREFIX_NAME"].ToString());
                    dic.Add("C5", dr["FIRST_NAME"].ToString());
                    dic.Add("C6", dr["LAST_NAME"].ToString());
                    dic.Add("F4", strCitizenId);
                    dic.Add("C7", main.ConvertNullDateTime(dr["BIRTH_DATE"]) != null ? main.ConvertNullDateTime(dr["BIRTH_DATE"]).Value.ToShortDateString() : "");
                    dic.Add("C9", main.ConvertNullDateTime(dr["RETIRE_DATE"]) != null ? main.ConvertNullDateTime(dr["RETIRE_DATE"]).Value.ToShortDateString() : "");
                    dic.Add("E6", "วันบรรจุ " + (main.ConvertNullDateTime(dr["DATE_ADMITTED"]) != null ? main.ConvertNullDateTime(dr["DATE_ADMITTED"]).Value.ToShortDateString() : ""));
                    dic.Add("G6", "6. ประเภทข้าราชการ " + dr["EMP_TYPE_NAME"].ToString());
                    dic.Add("F7", dr["father_name"].ToString());
                    dic.Add("F8", dr["mother_name"].ToString());
                    dic.Add("F9", dr["spouse_name"].ToString());
                    dic.Add("F10", dr["place_of_birth"].ToString());

                    DataTable dtbEdu = eduBLL.LoadEducationHistories((int?)null, nEmpSeq.ToString()).Tables[0];

                    for (int i = 0; i < 9 && i < dtbEdu.Rows.Count; i++)
                    {
                        DataRow drEdu = dtbEdu.Rows[i];

                        dic.Add("A" + (i + 13).ToString(), drEdu["EDU_INS_NAME"].ToString());
                        dic.Add("D" + (i + 13).ToString(), drEdu["EDU_START_YEAR"].ToString() + "-" + drEdu["EDU_END_YEAR"].ToString());
                        dic.Add("F" + (i + 13).ToString(), drEdu["EDU_DEGREE_NAME"].ToString() + " (" + drEdu["EDU_MAJOR_NAME"].ToString() + ")");
                    }

                    DataTable dtbDisc = cmdBLL.LoadCommandDetails(nEmpSeq, SystemInfo._HisDiscipline).Tables[0];

                    for (int i = 0; i < 3 && i < dtbDisc.Rows.Count; i++)
                    {
                        DataRow drDisc = dtbDisc.Rows[i];

                        dic.Add("A" + (i + 29).ToString(), drDisc["EDU_INS_NAME"].ToString());
                        dic.Add("C" + (i + 29).ToString(), main.ConvertNullDateTime(drDisc["start_date"]) != null ? main.ConvertNullDateTime(drDisc["start_date"]).Value.Year.ToString() : "");
                        dic.Add("G" + (i + 29).ToString(), drDisc["CMD_REF_NO"].ToString());
                    }

                    new MailMerge().MergeExcel(Response, Server.MapPath("~/Reports/Templates/กพ7.xlsx"), string.Format("กพ7-{0}", DateTime.Now.ToString("yyyyMMddHHmmssffff")), null, dic);
                }
            }
            else
            {
                main.MessageAlert(Page, "กรุณาเลือกบุคลากรที่ต้องการออกรายงาน");
            }
        }

        //protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        //{
        //    if (e.Item is GridDataItem)
        //    {
        //        DataSet ds = null;
        //        DataTable dt = null;
        //        DataSet[] dsSubReport = new DataSet[2];
        //        DataTable[] dtSubReport = new DataTable[2];

        //        GridDataItem item = (GridDataItem)e.Item;
        //        //int Sequence = Convert.ToInt32(item.GetDataKeyValue("emp_seq").ToString());

        //        int Sequence = Convert.ToInt32(item.OwnerTableView.DataKeyValues[item.ItemIndex]["emp_seq"].ToString());
                 

        //        //int Sequence = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["emp_seq"]);

        //        ds = empBLL.LoadEmployees(Sequence, "", true);
        //        if (ds.Tables.Count > 0)
        //            dt = ds.Tables[0].Copy();

        //        Session["dtReport"] = dt;

        //        //ประวัติการรับราชการ                    
        //        dsSubReport[0] = cmdBLL.LoadCommandDetails(Sequence, SystemInfo._HisPosition);
        //        if (dsSubReport[0].Tables.Count > 0)
        //            dtSubReport[0] = ds.Tables[0].Copy();

        //        //ประวัติการเลื่อนเงินเดือน                  
        //        dsSubReport[1] = cmdBLL.LoadCommandDetails(Sequence, SystemInfo._HisSalary);
        //        if (dsSubReport[1].Tables.Count > 0)
        //            dtSubReport[1] = ds.Tables[0].Copy();

        //        Session["dtSubReport"] = dtSubReport;

        //        LinkButton editLink = (LinkButton)e.Item.Cells[0].FindControl("targetControl");
        //        editLink.Attributes.Add("OnClientClick", "radopen('RPT_Exports.aspx?ReportName=RPT_PS_EmployeeDtls', 'RadWindow1');return false;"); 
            
        //        //((LinkButton)((GridDataItem)e.Item).ChildItem.FindControl("cmdPrint")).Attributes.Add("onclick", "radopen('RPT_Exports.aspx?ReportName=RPT_PS_EmployeeDtls', 'RadWindow1');return false;"); 
            
        //    }
        //}
    }
}
